<!--
Copyright (c) 2023 The Khronos Group Inc.
Use of this source code is governed by an MIT-style license that can be
found in the LICENSE.txt file.
-->

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Ensure 10bpc image is not crushed to 8bpc in texImage2D</title>
<link rel="stylesheet" href="../../../resources/js-test-style.css" />
<script src="../../../js/js-test-pre.js"></script>
<script src="../../../js/webgl-test-utils.js"></script>
</head>
<body>
<canvas id="example" width="24" height="24"></canvas>
<div id="description"></div>
<div id="console"></div>
<script>
"use strict";
description(document.title);
var wtu = WebGLTestUtils;
var gl = wtu.create3DContext("example", undefined, 2);
var uniquePixels;

// This is an 8x1, 10-bit-per-channel PNG (encoded as 16bpc).
// The first pixel is black, and each next pixel is one brighter; approximately:
// (0/1023,0,0), (1/1023,0,0), (2/1023,0,0), ..., (7/1023,0,0)
const imgW = 8, imgH = 1;
const imgURL = "../../../resources/red-gradient-8x1-10bit-untagged.png";

const img = document.createElement("img");
img.onload = () => {
  const tex = gl.createTexture();
  gl.bindTexture(gl.TEXTURE_2D, tex);
  const level = 0;
  const internalformat = gl.RGB10_A2;
  const border = 0;
  const format = gl.RGBA;
  const type = gl.UNSIGNED_INT_2_10_10_10_REV;
  gl.texImage2D(gl.TEXTURE_2D, level, internalformat, imgW, imgH, border, format, type, img);

  const fbo = gl.createFramebuffer();
  gl.bindFramebuffer(gl.FRAMEBUFFER, fbo);
  gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);

  shouldBe("gl.checkFramebufferStatus(gl.FRAMEBUFFER)", "gl.FRAMEBUFFER_COMPLETE");

  const pixels = new Uint32Array(imgW * imgH);
  gl.readPixels(0, 0, imgW, imgH, format, type, pixels);
  uniquePixels = new Set(pixels);
  // If the image was crushed to 8bpc, there will be 2-3 distinct values:
  // (0/255,0,0), (1/255,0,0), and maybe (2/255,0,0) (depending on truncation vs rounding).
  // If it wasn't, there should be 7-8.
  // At time of writing, on Mac M1, Chrome gets 2 if it's crushed, and 7 if it's not.
  shouldBeGreaterThanOrEqual("uniquePixels.size", "7", "there should be at least 7 distinct color values");

  finishTest();
};
img.src = imgURL;

var successfullyParsed = true;
</script>
</body>
</html>
